<?php

namespace App\Models;

use Illuminate\Support\Str;
use App\Models\AttributeColor;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'title','profile', 'description', 'image', 'on_sale','review_count','rating',
        'sold_count', 'price', 'category_id','stock','unit','video_url','sort'
    ];
    protected $casts = [
         'on_sale' => 'boolean', // on_sale 是一个布尔类型的字段
    ];
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    // 与商品SKU关联
    public function skus()
    {
        return $this->hasMany(ProductSku::class);
    }


    public function getFontImageAttribute()
    {
        // 如果 image 字段本身就已经是完整的 url 就直接返回
        if (Str::startsWith($this->attributes['font_image'], ['http://', 'https://'])) {
            return $this->attributes['font_image'];
        }
        return \Storage::disk('admin')->url($this->attributes['font_image']);
    }
    public function getCarouselImageAttribute($pictures)
    {
        return json_decode($pictures, true);
    }
    public function setCarouselImageAttribute($pictures)
    {
        if (is_array($pictures)) {
            $this->attributes['carousel_image'] = json_encode($pictures);
        }
    }
    // public function getColorInfoAttribute($value)
    // {
    //     $arr =  explode(',', $this->attributes['color']);
    //     $colors = AttributeColor::whereIn('id',$arr)->get();
    //     return $colors;
    // }
    // public function getColorAttribute($value)
    // {
    //     return  explode(',', $value);
    // }
    // public function setColorAttribute($value)
    // {
    //     $this->attributes['color'] = implode(',', $value);
    // }

    // public function getSizeAttribute($value)
    // {
    //     return explode(',', $value);
    // }

    // public function setSizeAttribute($value)
    // {
    //     $this->attributes['size'] = implode(',', $value);
    // }


    public function getImageUrl($value)
    {
        // 如果 image 字段本身就已经是完整的 url 就直接返回
        if (Str::startsWith($value, ['http://', 'https://'])) {
            return $value;
        }
        return \Storage::disk('admin')->url($value);
    }

}
